const QuestionCategory = require('../models/QuestionCategory');
const Question = require('../models/Question');
const { getTimestamp, getTwoDigits, formatObject } = require('../utils/common');
const { sendResponse, sendListResponse } = require('../utils/response');
const { Op } = require('sequelize');
const sequelize = require('../db/db');

// 新增(要求name跟之前的不一样)
exports.addQuestionCategory = async (req, res) => {
  const { name, sortOrder } = req.body;
  try {
    const existingCategory = await QuestionCategory.findOne({ where: { name } });
    if (existingCategory) {
      sendResponse(res, 400, "分类名称已存在");
      return;
    }
    const id = "183" + getTimestamp() + getTwoDigits();
    await QuestionCategory.create({
      id,
      name,
      sort_order: sortOrder,
    });
    sendResponse(res, 200, "新增成功");
  } catch (error) {
    console.error('新增失败', error);
    sendResponse(res, 500, "新增失败");
  }
}

// 删除
exports.deleteQuestionCategory = async (req, res) => {
  const { id } = req.body;
  try {
    // 开始事务
    const transaction = await sequelize.transaction();
    
    try {
      // 检查分类是否存在
      const questionCategory = await QuestionCategory.findByPk(id, { transaction });
      if (!questionCategory) {
        await transaction.rollback();
        sendResponse(res, 404, "分类不存在");
        return;
      }
      
      // 更新使用此分类的题目，将category_id置为null
      await Question.update(
        { category_id: null },
        { 
          where: { category_id: id },
          transaction
        }
      );
      
      // 删除分类
      await questionCategory.destroy({ transaction });
      
      // 提交事务
      await transaction.commit();
      
      sendResponse(res, 200, "删除成功");
    } catch (error) {
      // 回滚事务
      await transaction.rollback();
      throw error;
    }
  } catch (error) {
    console.error('删除失败', error);
    sendResponse(res, 500, "删除失败");
  }
}

// 修改(要求name跟之前的不一样)
exports.updateQuestionCategory = async (req, res) => {
  const { id, name, sortOrder, status } = req.body;
  try {
    const questionCategory = await QuestionCategory.findByPk(id);
    if (!questionCategory) {
      sendResponse(res, 404, "分类不存在");
      return;
    }
    if (name) {
      const existingCategory = await QuestionCategory.findOne({ where: { name } });
      if (existingCategory) {
        sendResponse(res, 400, "分类名称已存在");
        return;
      }
    }

    const params = {
      id,
    };
    if (name) {
      params.name = name;
    }
    if (sortOrder) {
      params.sort_order = sortOrder;
    }
    if (status) {
      params.status = status;
    }
    await questionCategory.update(params);
    sendResponse(res, 200, "修改成功", formatObject(questionCategory.toJSON()));
  } catch (error) {
    console.error('修改失败', error);
    sendResponse(res, 500, "修改失败");
  }
}

// 根据id查询
exports.getQuestionCategoryById = async (req, res) => {
  const id = req.params.id;

  try {
    const questionCategory = await QuestionCategory.findByPk(id);
    if (!questionCategory) {
      sendResponse(res, 404, "分类不存在");
      return;
    }
    sendResponse(res, 200, "查询成功", formatObject(questionCategory.toJSON()));
  } catch (error) {
    console.error('查询失败', error);
    sendResponse(res, 500, "查询失败");
  }
}


// 根据条件分页查询分类列表
exports.getQuestionCategoryList = async (req, res) => {
  const { page = 1, pageSize = 10, name, status } = req.query;

  try {
    const where = {};
    if (name) {
      where.name = {
        [Op.like]: `%${name}%`,
      };
    }
    if (status) {
      where.status = status;
    }
    const offset = (page - 1) * pageSize;
    const questionCategoryList = await QuestionCategory.findAndCountAll({
      where,
      offset,
      limit: parseInt(pageSize),
      order: [['sort_order', 'ASC'], ['create_time', 'ASC']],
    });
    const { count, rows } = questionCategoryList;
    const list = rows.map(item => {
      return formatObject(item.toJSON())
    })
    sendListResponse(res, 200, "查询成功", list, count);
  } catch (error) {
    console.error('查询失败', error);
    sendResponse(res, 500, "查询失败");
  }
}

// 获取所有分类列表，不分页
exports.getQuestionCategoryListAll = async (req, res) => {
  try {
    const questionCategoryList = await QuestionCategory.findAll({
      order: [['sort_order', 'ASC'], ['create_time', 'ASC']],
    });
    
    const list = questionCategoryList.map(item => {
      return formatObject(item.toJSON())
    });
    
    sendResponse(res, 200, "查询成功", list);
  } catch (error) {
    console.error('查询失败', error);
    sendResponse(res, 500, "查询失败");
  }
}

module.exports;